package br.com.carser.listeners;

import java.lang.reflect.Method;

import javax.el.ELResolver;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import br.com.carser.annotations.authorization.AllPresent;
import br.com.carser.annotations.authorization.AnyPresent;
import br.com.carser.annotations.authorization.NotPresent;

/**
 * Listener to verify permissions.
 * 
 * @author Eduardo T. Serete
 */
public class PermissionListener implements PhaseListener {

	/**
	 * Serial version.
	 */
	private static final long serialVersionUID = 8927523703366017348L;

	@Override
	public void afterPhase(PhaseEvent event) {
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		boolean valid = true;
		FacesContext context = event.getFacesContext();
		OUTER: for (String clientId : context.getExternalContext()
				.getRequestParameterMap().keySet()) {
			UIComponent component = context.getViewRoot().findComponent(
					clientId);
			if (component instanceof UICommand) {
				String expression = ((UICommand) component)
						.getActionExpression().getExpressionString();
				if (expression != null) {
					String clazz = expression.substring(
							expression.indexOf("#{") + 2,
							expression.indexOf("."));
					String methodName = ((UICommand) component)
							.getActionExpression()
							.getMethodInfo(context.getELContext()).getName();
					ELResolver resolver = FacesContext.getCurrentInstance()
							.getApplication().getELResolver();
					resolver.getValue(context.getELContext(), null, expression);
					Method[] methods = resolver
							.getValue(
									FacesContext.getCurrentInstance()
											.getELContext(), null, clazz)
							.getClass().getMethods();
					for (Method method : methods) {
						if (method.getName().equals(methodName)) {
							if (method.isAnnotationPresent(AllPresent.class)) {
								valid = validateAllPresent(method.getAnnotation(
										AllPresent.class).value());
							} else if (method.isAnnotationPresent(AnyPresent.class)) {
								valid = validateAnyPresent(method.getAnnotation(AnyPresent.class).value());
							} else if (method.isAnnotationPresent(NotPresent.class)) {
								valid = validateNotPresent(method.getAnnotation(NotPresent.class).value());
							}
							break OUTER;
						}
					}
				}
				break;
			}
		}
		if (!valid) {
			//TODO: Make the redirection
		} 
	}

	private boolean validateAllPresent(String... permissions) {
		return false;
	}
	
	private boolean validateAnyPresent(String... permissions) {
		return false;
	}

	private boolean validateNotPresent(String... permissions) {
		return false;
	}


	@Override
	public PhaseId getPhaseId() {
		return PhaseId.APPLY_REQUEST_VALUES;
	}

}
